package com.heima.media.listener;

import com.alibaba.fastjson.JSON;
import com.heima.media.entity.WmNews;
import com.heima.media.service.IAuditService;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author zsk
 * @create 2022-04-15-22:29
 */
@Service
public class ArticlePublishListener {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private IAuditService auditService;

    @PostConstruct
    public void handleMessage() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 获取一个阻塞队列  指定队列的名称
                RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque("article-publish");
                // 在监听器启动时先发一条自定义消息,主要是用于激活这个队列
                // 创建一个延迟队列 指定使用哪个阻塞队列
                RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
                delayedQueue.offer("init", 1, TimeUnit.SECONDS);

                while (true){
                    String msg =null;
                    // 拉取消息 指定超时时间 默认这个方法是阻塞的
                    try {
                        Object message = blockingDeque.poll(1, TimeUnit.MINUTES);
                        if (message!=null&& !message.equals("init")) {
                            System.out.println("接收到消息: " + message + ", " + new Date());
                            // 收到消息后  重新发布文章
                            auditService.audit((WmNews) message);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

            }
        }).start();
    }
}

